import datetime
import random

def init_user(money: int, goods: list):
    """初始化用户信息

    Args:
        money (int): 余额
        goods (list): 商品列表

    Returns:
        dict: 用户字典
    """    
    return {
        "money": money,
        "shopping_cart": [],
        "coupon": {
            "percentage": 0.8,
            "goods": random.choice(goods),
            "sum_cop": 0
        }
    }


def init_goods():
    """初始化商品列表

    Returns:
        dict: 商品列表
    """    
    return [
        {"id": 1, "name": "CPU", "price": 2000, "inventory": 5},
        {"id": 2, "name": "主板", "price": 1500, "inventory": 10},
        {"id": 3, "name": "散热器", "price": 500, "inventory": 15},
        {"id": 4, "name": "显卡", "price": 6000, "inventory": 20},
        {"id": 5, "name": "电源", "price": 1200, "inventory": 25},
        {"id": 6, "name": "内存", "price": 700, "inventory": 30},
        {"id": 7, "name": "硬盘", "price": 900, "inventory": 35},
        {"id": 8, "name": "机箱", "price": 200, "inventory": 40},
        {"id": 9, "name": "风扇", "price": 50, "inventory": 45},
        {"id": 10, "name": "支架", "price": 100, "inventory": 50},
        {"id": 11, "name": "鼠标", "price": 150, "inventory": 55},
        {"id": 12, "name": "键盘", "price": 200, "inventory": 60},
        {"id": 13, "name": "耳机", "price": 120, "inventory": 65},
        {"id": 14, "name": "显示器", "price": 1000, "inventory": 70}
    ]


def print_menu():
    """打印选项菜单
    """    
    print("[系统选项]".center(93, "*"))
    print("*", "1.购买商品".center(89, " "), "*")
    print("*", "2.商品退货".center(89, " "), "*")
    print("*", "3.查看商品".center(89, " "), "*")
    print("*", "4.查看购物".center(89, " "), "*")
    print("*", "5.退出系统".center(89, " "), "*")
    print("*"*97)


def print_goods(goods: list):
    """打印商品清单

    Args:
        goods (list): 商品列表
    """    
    print("[商品清单]".center(93, "*"))
    print("*\t商品ID", "\t\t\t商品名称",  "\t\t\t商品价格", "\t\t库存\t*")
    for g in goods:
        print("*", end='\t')
        print("%3d" % g["id"], end='\t\t\t')
        print(g["name"], end='\t\t\t\t')
        print("%6d" % g["price"], end='\t\t\t')
        print("%3d" % g["inventory"], end='\t')
        print('*')
    print("*"*97)


def print_cart(user: dict, goods: list):
    """打印用户购物车

    Args:
        user (dict): 用户字典
        goods (list): 商品清单列表
    """    
    all_sum = 0
    print("[购物]".center(95, "*"))
    print("*\t商品ID", "\t\t商品名称",  "\t\t商品价格", "\t\t数量", "\t\t总计\t*")
    for cg in user["shopping_cart"]:

        print("*", end='\t')
        print("%3d" % cg["id"], end='\t\t')
        print(cg["name"], end='\t\t\t')
        print("%6d" % cg["price"], end='\t\t\t')
        print("%3d" % cg["count"], end='\t\t')
        print("%5d" % cg["sum"], end='\t')
        print('*')
        all_sum += cg["sum"]

    now = datetime.datetime.now()
    formatted_date = now.strftime("%Y年%m月%d日")
    print("*", " "*93, "*")
    print("*", f"总合计: ", f"{all_sum:.1f}".rjust(80, " "), "\t*")
    print("*", f"卡余额: ", f"{user["money"]:.1f}".rjust(80, " "), "\t*")
    print("*", f"共优惠: ", f"{user["coupon"]["sum_cop"]:.1f}".rjust(80, " "), "\t*")
    print("*", f"时间: ", "\t"*9, f"{formatted_date}", "*")
    print("*"*97)


def buy_goods(user: dict, goods: dict):
    """购买商品

    Args:
        user (dict): 用户字典
        goods (dict): 商品字典
    """    
    coupon = user["coupon"]

    if user['money'] < goods["price"]:
        if goods["id"] == coupon["goods"]["id"]:
            if user['money'] < goods["price"] * coupon["percentage"]:
                print("穷鬼，钱不够！请到其他超市购买！")
                return
        else:
            print("穷鬼，钱不够！请到其他超市购买！")
            return

    if goods["inventory"] <= 0:
        print("没有这个商品，别瞎弄！")
        return

    else:
        is_add = False
        
        target = {
            "id": goods["id"],
            "name": goods["name"],
            "price": goods["price"],
            "count": 1,
            "sum": goods["price"]
        }

        for i in range(len(user["shopping_cart"])):
            u_cart = user["shopping_cart"][i]

            if u_cart["id"] == goods["id"]:
                u_cart["count"] += 1

                if goods["id"] == coupon["goods"]["id"]:
                    price = goods["price"] * coupon["percentage"]
                    coupon["sum_cop"] = (goods["price"] *  u_cart["count"]) - price * u_cart["count"]
                else:
                    price = goods["price"]
                
                goods["inventory"] -= 1
                user["money"] -= price
                u_cart["sum"] = price * u_cart["count"]

                print("恭喜，购买成功！您的卡余额还剩: {}".format(user["money"]))
                return
        else:
            is_add = True

        if len(user["shopping_cart"]) == 0 or is_add:

            if goods["id"] == coupon["goods"]["id"]:
                price = goods["price"] * coupon["percentage"]
                coupon["sum_cop"] = (goods["price"] *  target["count"]) - price * target["count"]
            else:
                price = goods["price"]
            
            goods["inventory"] -= 1
            user["money"] -= price
            target["sum"] = price * target["count"]
            user["shopping_cart"].append(target)
            print("恭喜，购买成功！您的卡余额还剩: {}".format(user["money"]))


def reject_goods(user: dict, goods: dict):
    """商品退货

    Args:
        user (dict): 用户字典
        goods (dict): 商品字典
    """    
    cart = user["shopping_cart"]
    coupon = user["coupon"]

    for g in cart:
        if g["id"] == goods["id"]:
            goods["inventory"] += 1
            g["count"] -= 1

            if goods["id"] == coupon["goods"]["id"]:
                price = goods["price"] * coupon["percentage"]
                coupon["sum_cop"] = (goods["price"] *  g["count"]) - price * g["count"]
            else:
                price = goods["price"]

            g["sum"] = price * g["count"]
            user["money"] += price
            print("恭喜，退货成功！您的卡余额还剩: {}".format(user["money"]))

            if g["count"] <= 0:
                cart.remove(g)
            return
    print("购物车中没有该商品，无法退货。")


def shopping_system_v1():
    """购物系统版本1
    """    
    goods = init_goods()
    user = init_user(10000)

    print_goods(goods)
    print("欢迎使用购物系统，选择购买的商品ID即可购买，输入'q'或者'Q'即可退出系统！")
    while True:
        value = input("请输入: ")
        if not value.isdigit():
            if value.lower() == "q":
                print_cart(user, goods)
                return
            else:
                print("无效的输入！")
                continue
        value = int(value)

        if value > len(goods):
            print("无效的商品ID！")
            continue

        buy_goods(user, goods[value - 1])


def shopping_system_v2():
    """购物系统版本2
    """    
    goods = init_goods()
    user = init_user(10000, goods)
    is_continue = True
    coupon = user["coupon"]
    print(f"欢迎使用！恭喜您抽到商品: {coupon["goods"]["id"]}.{coupon["goods"]["name"]}的{coupon["percentage"] * 10}折优惠劵！")
    while is_continue:
        print_menu()
        option = input("请输入操作选项: ")
        if not option.isdigit():
            print("无效的输入！")
            continue
        option = int(option)

        if option == 1:
            print_goods(goods)
            goods_id = input("商品ID: ")
            if not goods_id.isdigit():
                print("无效的输入！")
                continue
            goods_id = int(goods_id)
            buy_goods(user, goods[goods_id - 1])

        elif option == 2:
            print_cart(user, goods)
            goods_id = input("商品ID: ")
            if not goods_id.isdigit():
                print("无效的输入！")
                continue
            goods_id = int(goods_id)
            reject_goods(user, goods[goods_id - 1])

        elif option == 3:
            print_goods(goods)

        elif option == 4:
            print_cart(user, goods)

        elif option == 5:
            print_cart(user, goods)
            print("感谢使用，欢迎下次光临！")
            return
        else:
            print("无效选项！")


if __name__ == '__main__':
    # shopping_system_v1()
    shopping_system_v2()
